import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import * as serverActions from '../utils/serverActions'
import { saveToFile, loadFromFile, uploadConfigFile } from '../utils/fileStorage'

export interface Service {
  id: number
  name: string
  description: string
  path: string
  port: number
  domain: string
  status: 'running' | 'stopped'
  scripts?: {
    start: string
    stop: string
    restart: string
    status: string
  }
}

export const useServiceStore = defineStore('services', () => {
  // 初始化一个空的服务数组，不再预置测试数据
  const services = ref<Service[]>([])

  // 保存服务列表到本地存储
  const saveToLocalStorage = () => {
    localStorage.setItem('services', JSON.stringify(services.value))
  }

  // 从本地存储加载服务列表
  const loadFromLocalStorage = () => {
    const savedServices = localStorage.getItem('services')
    if (savedServices) {
      services.value = JSON.parse(savedServices)
    }
  }

  // 保存服务列表到项目内的JSON文件
  const saveToJsonFile = () => {
    // 在浏览器环境下，这会下载配置文件，用户需手动替换项目中的文件
    return saveToFile(services.value)
  }

  // 从项目内的JSON文件加载服务列表
  const loadFromJsonFile = async () => {
    try {
      const loadedServices = await loadFromFile<Service[]>()
      if (loadedServices && loadedServices.length > 0) {
        services.value = loadedServices
        // 同时更新localStorage
        saveToLocalStorage()
        return true
      } else {
        console.log('配置文件为空或未找到，使用默认设置')
        return false
      }
    } catch (error) {
      console.error('加载配置文件失败', error)
      return false
    }
  }

  // 从用户上传的JSON文件导入服务列表
  const importFromUploadedFile = async () => {
    try {
      const loadedServices = await uploadConfigFile<Service[]>()
      if (loadedServices && loadedServices.length > 0) {
        services.value = loadedServices
        // 同时更新localStorage
        saveToLocalStorage()
        return true
      }
      return false
    } catch (error) {
      console.error('导入上传的配置文件失败', error)
      return false
    }
  }

  // 初始化时尝试按优先级顺序加载配置:
  // 1. 尝试从项目内的config.json加载
  // 2. 如果失败，尝试从localStorage加载
  const initializeServices = async () => {
    try {
      // 首先尝试从项目内config.json加载
      const configLoaded = await loadFromJsonFile()
      
      // 如果从config.json加载失败，尝试从localStorage加载
      if (!configLoaded) {
        loadFromLocalStorage()
      }
    } catch (e) {
      console.error('初始化服务列表失败', e)
      // 如果所有加载方式都失败，至少尝试从localStorage加载
      try {
        loadFromLocalStorage()
      } catch (error) {
        console.error('从localStorage加载失败', error)
      }
    }
  }

  // 项目初始化时加载服务列表
  initializeServices()

  const getServiceById = (id: number) => {
    return services.value.find(service => service.id === id)
  }

  const addService = (service: Omit<Service, 'id'>) => {
    const newId = Math.max(0, ...services.value.map(s => s.id)) + 1
    services.value.push({
      ...service,
      id: newId
    })
    saveToLocalStorage()
    return newId
  }

  const updateService = (id: number, updatedService: Partial<Service>) => {
    const index = services.value.findIndex(service => service.id === id)
    if (index !== -1) {
      services.value[index] = {
        ...services.value[index],
        ...updatedService
      }
      saveToLocalStorage()
      return true
    }
    return false
  }

  const deleteService = (id: number) => {
    const index = services.value.findIndex(service => service.id === id)
    if (index !== -1) {
      services.value.splice(index, 1)
      saveToLocalStorage()
      return true
    }
    return false
  }

  const startService = async (id: number) => {
    const service = getServiceById(id)
    if (!service) return false
    
    let success = false
    if (service.scripts?.start) {
      // 使用自定义脚本启动服务
      success = await serverActions.executeScript(service.scripts.start)
    } else {
      // 使用默认方法启动服务
      success = await serverActions.startService(service.path, service.port)
    }
    
    if (success) {
      updateService(id, { status: 'running' })
    }
    
    return success
  }

  const stopService = async (id: number) => {
    const service = getServiceById(id)
    if (!service) return false
    
    let success = false
    if (service.scripts?.stop) {
      // 使用自定义脚本停止服务
      success = await serverActions.executeScript(service.scripts.stop)
    } else {
      // 使用默认方法停止服务
      success = await serverActions.stopService(service.path, service.port)
    }
    
    if (success) {
      updateService(id, { status: 'stopped' })
    }
    
    return success
  }

  const restartService = async (id: number) => {
    const service = getServiceById(id)
    if (!service) return false
    
    let success = false
    if (service.scripts?.restart) {
      // 使用自定义脚本重启服务
      success = await serverActions.executeScript(service.scripts.restart)
    } else {
      // 使用默认方法重启服务
      success = await serverActions.restartService(service.path, service.port)
    }
    
    return success
  }

  const checkServiceStatus = async (id: number) => {
    const service = getServiceById(id)
    if (!service) return false
    
    let isRunning = false
    if (service.scripts?.status) {
      // 使用自定义脚本检查服务状态
      isRunning = await serverActions.executeScript(service.scripts.status)
    } else {
      // 使用默认方法检查服务状态
      isRunning = await serverActions.checkServiceStatus(service.path, service.port)
    }
    
    // 更新服务状态
    updateService(id, { status: isRunning ? 'running' : 'stopped' })
    
    return isRunning
  }

  const refreshAllServices = async () => {
    const promises = services.value.map(service => checkServiceStatus(service.id))
    return Promise.all(promises)
  }

  const updateServiceScripts = (serviceId: number, scripts: Service['scripts']) => {
    return updateService(serviceId, { scripts })
  }

  const runningServices = computed(() => {
    return services.value.filter(service => service.status === 'running')
  })

  const stoppedServices = computed(() => {
    return services.value.filter(service => service.status === 'stopped')
  })

  return {
    services,
    getServiceById,
    addService,
    updateService,
    deleteService,
    startService,
    stopService,
    restartService,
    checkServiceStatus,
    refreshAllServices,
    updateServiceScripts,
    runningServices,
    stoppedServices,
    saveToJsonFile,
    loadFromJsonFile,
    importFromUploadedFile
  }
}) 